/**
 * @author 小徐
 * @create 2020-06-20 20:08
 */
public class A616a {
    public static void main(String[] args) {

        String[] s ={"adoo","rdooacecar","cdooar"};

        Solution616a so = new Solution616a();
        System.out.println(so.longestCommonPrefix(s));

    }
}

/**
 * 横向扫描法！！
 * 执行结果：通过  显示详情
 执行用时：1 ms, 在所有 Java 提交中击败了81.18%的用户
 内存消耗：37.8 MB, 在所有 Java 提交中击败了25.00%的用户
 */
/*
class Solution616a {
    public String longestCommonPrefix(String[] strs) {

        if(strs == null || strs.length == 0) return "";

        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            prefix = getPrefix(prefix,strs[i]);
            if(prefix.length() == 0){
                prefix = "";
            }
        }
        return prefix;
    }

    public String getPrefix(String s1,String s2){
        int sLength = Math.min(s1.length(),s2.length());
        int index = 0;
        for (int i = 0; i < sLength; i++) {
            if(s1.charAt(i) == s2.charAt(i) && index == i ){
                index ++;
            }
        }
        return s1.substring(0,index);

    }
}
*/

/**
 * 官方解答，就是不一样
 */
class Solution616a {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        int count = strs.length;
        for (int i = 1; i < count; i++) {
            prefix = longestCommonPrefix(prefix, strs[i]);
            if (prefix.length() == 0) {
                break;
            }
        }
        return prefix;
    }

    public String longestCommonPrefix(String str1, String str2) {
        int length = Math.min(str1.length(), str2.length());
        int index = 0;
        /**
         * 这个while循环体太妙了！！！！
         */
        while (index < length && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);
    }
}



